import { Component, OnInit } from '@angular/core';
import { NetService } from './../../services/net.service';

@Component({
  selector: 'app-static-list',
  templateUrl: './static-list.component.html',
  styleUrls: ['./static-list.component.scss']
})
export class StaticListComponent implements OnInit {
  fileList = [];
  filePath = [];
  currentList = [];
  filePathString = '';
  constructor(private net: NetService) { }

  clickPath(item, i) {
    this.currentList = this.fileList.filter(im => im && im.parentId === item.id);
    if (this.filePath.length !== 1) {
      this.filePath = this.filePath.slice(0, i + 1);
    }
  }

  uploadOk() {
    this.updateList();
  }
  async updateList() {
    const result = await this.net.get('/api/statics');
    if (result) {
      this.fileList = result['data'];
      const lastFilePath = this.filePath[this.filePath.length - 1];
      if (!lastFilePath) {
        this.currentList = this.fileList.filter(item => item && item.parentId === '');
      } else {
        const parent = this.fileList.filter(item => item && item.name === this.filePath[this.filePath.length - 1].name);
        this.currentList = this.fileList.filter(item => item && parent[0] && item.parentId === parent[0].id);
      }
    }
  }

  changePath(item) {
    this.filePath.push(item);
    this.currentList = this.fileList.filter(im => im && im.parentId === item.id);
    this.filePathString = this.filePath.map(im => im.name).join('/');
  }

  isPic(link) {
    let pic = false;
    const types = ['.gif', '.jpeg', '.png', '.jpg', '.bmp', '.svg'];
    types.forEach(item => {
      if (link.indexOf(item) > -1) {
        pic = true;
      }
    });
    return pic;
  }
  async getFileList() {
    const result = await this.net.get('/api/statics');
    if (result) {
      this.fileList = result['data'];
      this.currentList = this.fileList.filter(item => item && item.parentId === '');
    }
    this.filePath = [];
    this.filePathString = '';
  }

  ngOnInit() {
    this.getFileList();
  }

}
